package com.aust.lambda;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;

public class TestLambda11 {

    /**
     * 对集合中的每个元素应用转换函数
     *
     * @param list
     * @param transformer
     * @param <T>
     * @param <R>
     * @return
     */
    public static <T, R> List<R> transform(List<T> list, Function<T, R> transformer) {
        List<R> result = new ArrayList<>();
        for (T item : list) {
            result.add(transformer.apply(item));
        }
        return result;
    }

    public static void main(String[] args) {

        List<String> name = Arrays.asList("Alice", "Bob", "Charlie");

        /**
         * 转换1：获取名字长度
         */
        List<Integer> integers = transform(name, String::length);
        System.out.println(integers);

        /**
         * 转换2：名字转大写
         */
        List<String> strings = transform(name, String::toUpperCase);
        System.out.println(strings);

        /**
         * 转换3：自定义格式
         */
        List<String> list = transform(name, new Function<String, String>() {
            @Override
            public String apply(String string) {
                for (int i = 0; i < string.length(); i++) {
                    System.out.println(i + ": " + string.charAt(i));
                }
                return "Hello" + string;
            }
        });
        System.out.println(list);

    }

}
